//解决IE8及之前浏览器不支持Date.now的BUG
if (!Date.now) {
    Date.now = function() {
        return new Date().valueOf();
    }
}
var localTime = +Date.now();
var SG = {
    module: {
        "core.form": "jquery.formvalidator",
        "tools.imgareaselect": "jquery.imgareaselect",
        "tools.marquee": "jquery.marquee",
        "tools.dialog": "jquery.dialog",
        "tools.autocomplete": "jquery.autocomplete",
        "tools.datepicker": "jquery.datepicker",
        "tools.dragsort": "jquery.dragsort",
        "tools.zeroclipboard": "zeroclipboard"
    },
    _loadModule: [],
    _loadedModule: [],
    init: function(module, fn) {
        if (arguments.length == 1 && module.constructor == Function) {
            fn = module;
            module = "";
        }
        var flag = [],
        timer = 0,
        overtime = 10, //超时秒数
        arr_module = module.split(",");
        var self = this;
        if (module) {
            $.each(arr_module, function(n, item) {
                if (self._loadModule.unique().include(item)) return;
                self._loadModule.push(item);
                if (!self._loadedModule.include(item)) {
                    self.include("/js/" + self.module[item] + ".js", function() {
                        switch (item) {
                            case "core.form":
                                $.extend(true, $.formValidator.settings, {
                                    alertmessage: false,
                                    autotip: true,
                                    errorfocus: false,
                                    submitonce: false
                                });
                                self._loadedModule.push(item);
                                self.include("/css/jquery.formvalidator.css");
                                break;
                            case "tools.imgareaselect":
                                self.include("/css/jquery.imgareaselect.css");
                                self._loadedModule.push(item);
                                break;
                            case "tools.dialog":
                                self.include("/css/jquery.dialog.css");
                                self._loadedModule.push(item);
                                break;
                            case "tools.autocomplete":
                                self.include("/css/jquery.autocomplete.css");
                                self._loadedModule.push(item);
                                break;
                            default:
                                self._loadedModule.push(item);
                                break;
                        }
                    });
                }
            });
        }
        var checkInterval = setInterval(function() {
            if (this._loadedModule.length == $.merge(this._loadModule, this._loadedModule).unique().length || timer / 10 > overtime) {
                clearInterval(checkInterval);
                typeof fn == "function" ? fn() : eval(fn);
            }
            timer++;
        } .bind(this), 100);
    },
    include: function(url, callback) {
        var afile = url.toLowerCase().replace(/^\s|\s$/g, "").match(/([^\/\\]+)\.(\w+)$/);
        url = url.substr(0,7)=='http://' ? url : SG.config.res_url + url + "?v=" + SG.config.version;
        if (!afile) return false;
        switch (afile[2]) {
            case "css":
                var el = $('<link rel="stylesheet" id="' + afile[1] + '" type="text/css" />').appendTo("head").attr("href", url);
                if ($.browser.msie) {
                    el.load(function() {
                        if (typeof callback == 'function') callback();
                    });
                } else {
                    var i = 0;
                    var checkInterval = setInterval(function() {
                        if ($("head>link").index(el) != -1) {
                            if (i < 10) clearInterval(checkInterval)
                            if (typeof callback == 'function') callback();
                            i++;
                        }
                    }, 200);
                }
                break;
            case "js":
                $.ajax({
                    global: false,
                    cache: true,
                    ifModified: false,
                    dataType: "script",
                    url: url,
                    success: callback
                });
                break;
            default:
                break;
        }
    },
    //背景颜色渐变
    bganimation: function(obj,seconds,bg,fromcolor,focus) {
        seconds = seconds ? seconds : 1000;
        obj.stop(false, true);
        fromcolor = fromcolor ? fromcolor : "#FFC8C8";
        bg = bg ? bg : obj.css("backgroundColor");
        focus = focus != undefined ? focus : true;
        if(focus){
            obj.focus();
        }
        obj.css({
            backgroundColor: fromcolor
        }).animate({
            backgroundColor: bg
        }, seconds);
        return false;
    },
    tools: {
        copy: function(txt) {
            //复制到剪贴板
            if (window.clipboardData) {
                window.clipboardData.clearData();
                window.clipboardData.setData("Text", txt);
            } else if (navigator.userAgent.indexOf("Opera") != -1) {
                window.location = txt;
            } else if (window.netscape) {
                try {
                    netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
                } catch (e) {
                    alert("您的firefox安全限制限制您进行剪贴板操作，请打开'about:config'将signed.applets.codebase_principal_support'设置为true'之后重试");
                    return false;
                }
                var clip = Components.classes['@mozilla.org/widget/clipboard;1'].createInstance(Components.interfaces.nsIClipboard);
                if (!clip) return false;
                var trans = Components.classes['@mozilla.org/widget/transferable;1'].createInstance(Components.interfaces.nsITransferable);
                if (!trans) return false;
                trans.addDataFlavor('text/unicode');
                var str = new Object();
                var len = new Object();
                var str = Components.classes['@mozilla.org/supports-string;1'].createInstance(Components.interfaces.nsISupportsString);
                var copytext = txt;
                str.data = copytext;
                trans.setTransferData("text/unicode", str, copytext.length * 2);
                var clipid = Components.interfaces.nsIClipboard;
                if (!clip) return false;
                clip.setData(trans, null, clipid.kGlobalClipboard);
            }
            return true;
        },
        in_array:function(value, array){
            //判断是否在数组中
            var i;
            for (i = 0; i < array.length; i++) {
                if (value === array[i]) {
                    return i;
                }
            }
            return false;
        },
        string: {
            //字符串操作
            format: function() {
                if (arguments.length == 0) return "";
                var args = arguments;
                var str = args[0];
                return str.replace(/\{(\d+)\}/gm, function() {
                    return args[parseInt(arguments[1]) + 1];
                });
            },
            length: function(str){
                var len = 0;
                for (var i = 0; i < str.length; i++) {
                    if (str.charCodeAt(i) >= 0x4e00 && str.charCodeAt(i) <= 0x9fa5) {
                        len += 2;
                    } else {
                        len++;
                    }
                }
                return len;
            }
        },
        hashString: function(item) {
            //获取中的地址参数
            if (!item) return location.hash.substring(1);
            var sValue = location.hash.match(new RegExp("[\#\&]" + item + "=([^\&]*)(\&?)", "i"));
            sValue = sValue ? sValue[1] : "";
            return sValue == location.hash.substring(1) ? "" : sValue == undefined ? location.hash.substring(1) : decodeURIComponent(sValue);
        },
        cookie: function(name, value, options) {
            //COOKIE操作
            if (typeof value != 'undefined') {
                options = options || {};
                if (value === null) {
                    value = '';
                    $.extend({}, options);
                    options.expires = -1;
                }
                var expires = '';
                if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
                    var date;
                    if (typeof options.expires == 'number') {
                        date = new Date();
                        date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
                    } else {
                        date = options.expires;
                    }
                    expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
                }
                var path = options.path ? '; path=' + (options.path) : '';
                var domain = options.domain ? '; domain=' + (options.domain) : '';
                var secure = options.secure ? '; secure' : '';
                document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
            } else {
                var cookieValue = '';
                if (document.cookie && document.cookie != '') {
                    var cookies = document.cookie.split(';');
                    for (var i = 0; i < cookies.length; i++) {
                        var cookie = cookies[i].trim();
                        if (cookie.substring(0, name.length + 1) == (name + '=')) {
                            cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                            break;
                        }
                    }
                }
                return cookieValue;
            }
        },
        tips:function(text,left,top,arrow,loc,obj,closefunc){
            //温馨提示
            var id=left+'_'+top+'_'+arrow+'_'+loc;
            var c = '<div id="tips_'+id+'" class="newtips" style="top: '+top+'px; left: '+left+'px; ">';
            c = c + '<div class="tipcontainer" style="opacity: 1; ">';
            c = arrow == 'up' ? c + '<span class="arrowup" style="margin-left: '+loc+'px; "></span>' : c;
            c = c + '<div class="t_container"><div class="tcc"><div class="t_content">';
            c = c + '<div class="tipsicon "><span class="tipsico tipsico_normal"></span></div>';
            c = c + '<div class="tipstxt"><span class="black">'+text+'</span></div>';
            c = c + '<div class="tipsrightpanel"><div class="opertbar"><a class="" id="close_'+id+'" href="javascript:;">我知道了</a></div></div>';
            c = c + '<div class="clear"></div>';
            c = c + '</div></div></div>';
            c = arrow == 'down' ?  c + '<span class="arrowdown" style="display:none; margin-left: '+loc+'px; "></span>' : c;
            c = c + '</div></div>';

            $(c).appendTo((obj!=undefined && obj!='' ? obj : document.body));
            $("#close_"+id).live("click",function(){
                $("#tips_"+id).hide().remove();
                if(closefunc!=undefined){
                    closefunc();
                }
            });
        },
        replace:function(str){
            //批量替换
            while (str.indexOf(sptr) >= 0) {
                str = str.replace(sptr, sptr1);
            }
            return str;
        },
        zoomChange:function(o){
            var s = o.scale;
            if(s!=undefined){
                var m = s > 1 ? '放大了': '缩小了';
                if(s != 1){
                    level = s;
                    $("#zoomtips").html("温馨提示：由于您的浏览器窗口" + m+"，为了页面能正常显示，请按Ctrl+数字键0恢复默认大小。").fadeIn();
                }else{
                    if (s != level) {
                        $("#zoomtips").hide('fast');
                    }
                }
            }
        }
    },
    checkAll: function(obj, elName) { 
        //选中所有
        $(obj).closest("form").find("input:checkbox[name=" + elName + "]").attr("checked", $(obj).attr("checked"));
    },
    insertSelection: function(obj, str) { 
        //在光标位置插入数据 obj为dom元素
        var tc = obj;
        var tclen = tc.value.length;
        tc.focus();
        if (typeof document.selection != "undefined") {
            document.selection.createRange().text = str;
            obj.createTextRange().duplicate().moveStart("character", -str.length);
        } else {
            var m = tc.selectionStart;
            tc.value = tc.value.substr(0, tc.selectionStart) + str + tc.value.substring(tc.selectionStart, tclen);
            tc.selectionStart = m + str.length;
            tc.setSelectionRange(m + str.length, m + str.length);
        }
    },
    addFavourite: function() {
        //添加进收藏夹
        var a = location.href;
        var b = "三国战记";
        if (document.all) {
            window.external.AddFavorite(a, b)
        } else if (window.sidebar) {
            window.sidebar.addPanel(b, a, "")
        } else {
            SG.dialog.notice("对不起，您的浏览器不支持此操作!\n请您拖动该链接到收藏夹或使用Ctrl+D收藏本站。");
        }
    },
    openWindow: function(url, width, height) {
        //弹出窗口
        var top=($(window).height()-height)/2;
        var left=($(window).width()-width)/2;
        var popup = window.open(url,'', 'height='+height+', width='+width+', toolbar =no, menubar=no, scrollbars=yes, resizable=yes,top='+top+',left='+left+', location=no, status=no');
        return popup;
    },
    getDirName:function(file_src) {
        //获取文件路径
        var dir=''
        ns = file_src.split("/")
        for (i=0;i<ns.length-1;i++) {
            dir = dir + ns[i] + '/' 
        }
        return dir;
    },
    tabs: {	//选项卡
        bind: function(obj, cobj) {
            //普通选项卡切换
            $("ul:eq(0)>li", obj).live("hover",function() {
                var _class = this.className.split(" ");
                if ($.inArray("none", _class) == -1 && $.inArray("more", _class) == -1) {
                    var _index = $(this).parent().children(":not(.more,.none)").index($(this).addClass("current").siblings().removeClass("current").end()[0]);
                    //var tab_content = $(obj).siblings(cobj);//取消同级参考
                    var tab_content = $(cobj);
                    if (tab_content.length > 0)
                        tab_content.hide().eq(_index).show();
                }
            });
            //子选项卡
            $("ul.tabs_sub>li>a", obj).live("hover",function() {
                var _this = $(this).parent();
                var _class = _this[0].className.split(" ");
                if ($.inArray("none", _class) == -1) {
                    _this.addClass("curr").siblings().removeClass("curr");
                }
            });
            //更多
            if ($(".more_list li", obj).length > 0) {
                $("li.more>a:eq(0)", obj).click(function() {
                    var _this = $(".more_list", obj);
                    _this.toggle().out("click", function(e) {
                        var found = $(e.target).closest(_this).length || e.target == this;
                        if (found == 0) _this.hide();
                    } .bind(this), true);
                });
            }
        }
    },
    time:{
        prezero:function(s, l){ //补前导零
            s = s.toString();
            for(i=0;i<l-s.length;i++) s = 0 + s;
            return s;
        },
        update:function(obj, timestamp){ //本地时间
            if(timestamp){
                var serverTime = parseFloat(timestamp+"000");
                var timeDiff = serverTime - localTime;
                var d = new Date(+Date.now() + timeDiff);
            }else{
                var d = new Date();
            }
            var hours = SG.time.prezero(d.getHours(),2);
            var minutes = SG.time.prezero(d.getMinutes(),2);
            var seconds = SG.time.prezero(d.getSeconds(),2);
            var day = SG.time.prezero(d.getDate(),2);
            var month = SG.time.prezero(d.getMonth() + 1,2);
            var year = d.getFullYear();
            $(obj).html(year + "-" + month + "-" + day + " " + hours + ":" + minutes + ":" + seconds);
            setTimeout(function(){
                SG.time.update(obj, timestamp);
            },1000);
        }
    }
};

(function(jQuery){
    jQuery.each(['backgroundColor', 'borderBottomColor', 'borderLeftColor', 'borderRightColor', 'borderTopColor', 'color', 'outlineColor'], function(i,attr){
        jQuery.fx.step[attr] = function(fx){
            if ( fx.state == 0 ) {
                fx.start = getColor( fx.elem, attr );
                fx.end = getRGB( fx.end );
            }
            fx.elem.style[attr] = "rgb(" + [
            Math.max(Math.min( parseInt((fx.pos * (fx.end[0] - fx.start[0])) + fx.start[0]), 255), 0),
            Math.max(Math.min( parseInt((fx.pos * (fx.end[1] - fx.start[1])) + fx.start[1]), 255), 0),
            Math.max(Math.min( parseInt((fx.pos * (fx.end[2] - fx.start[2])) + fx.start[2]), 255), 0)
            ].join(",") + ")";
        }
    });
    function getRGB(color) {
        var result;
        if ( color && color.constructor == Array && color.length == 3 )
            return color;
        if (result = /rgb\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*\)/.exec(color))
            return [parseInt(result[1]), parseInt(result[2]), parseInt(result[3])];
        if (result = /rgb\(\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*\)/.exec(color))
            return [parseFloat(result[1])*2.55, parseFloat(result[2])*2.55, parseFloat(result[3])*2.55];
        if (result = /#([a-fA-F0-9]{2})([a-fA-F0-9]{2})([a-fA-F0-9]{2})/.exec(color))
            return [parseInt(result[1],16), parseInt(result[2],16), parseInt(result[3],16)];
        if (result = /#([a-fA-F0-9])([a-fA-F0-9])([a-fA-F0-9])/.exec(color))
            return [parseInt(result[1]+result[1],16), parseInt(result[2]+result[2],16), parseInt(result[3]+result[3],16)];
        return "";
    }
    function getColor(elem, attr) {
        var color;
        do {
            color = jQuery.curCSS(elem, attr);
            if ( color != '' && color != 'transparent' || jQuery.nodeName(elem, "body") )
                break;
            attr = "backgroundColor";
        } while ( elem = elem.parentNode );
        return getRGB(color);
    };
})(jQuery);
//text文本框插入代码
//来源:http://hi.baidu.com/see7di/home
(function($){
    $.fn.insert=function(text){
        var _o=$(this).get(0);
        if($.browser.msie){
            _o.focus();
            sel=document.selection.createRange();
            sel.text=text;
            sel.select();
        }else if(_o.selectionStart || _o.selectionStart == '0'){
            var startPos=_o.selectionStart;
            var endPos=_o.selectionEnd;
            var restoreTop=_o.scrollTop;
            _o.value=_o.value.substring(0, startPos) + text + _o.value.substring(endPos,_o.value.length);
            if (restoreTop>0){
                _o.scrollTop=restoreTop;
            }
            _o.focus();
            _o.selectionStart=startPos+text.length;
            _o.selectionEnd=startPos+text.length;
        }
    };
})(jQuery);
//移除 layerX && layerY
//来源:互联网
(function(){
    var all = $.event.props,
    len = all.length,
    res = [];
    while (len--) {
        var el = all[len];
        if (el != 'layerX' && el != 'layerY') res.push(el);
    }
    $.event.props = res;
}());
//图片切换插件 by Karson
jQuery.fn.slideshow = function(attr) {
    attr = attr || {};
    attr.duration = attr.duration || 3000;
    function slideshow(_o){
        $("a:first", _o).appendTo($(_o));
        $("img", _o).css({
            'z-index':0
        });
        $(_o).find('img:first').css({
            opacity: 0.0, 
            'z-index': 2
        }).animate({
            opacity: 1.0
        }, 1000, function() {
            setTimeout( function(){
                slideshow(_o);
            }, attr.duration );
        });
    }
    var _o = this;
    $("img:first", _o).css({
        'z-index':2
    });
    setTimeout( function(){
        slideshow(_o);
    }, attr.duration );
};

//判断是否为IE6
$.browser.msie6 = $.browser.msie && /MSIE 6\.0/i.test(window.navigator.userAgent) && !/MSIE 7\.0/i.test(window.navigator.userAgent);

//函数扩展
Function.prototype.bind = function() {	//绑定域
    var method = this,
    _this = arguments[0],
    args = [];
    for (var i = 1,
        il = arguments.length; i < il; i++) {
        args.push(arguments[i]);
    }
    return function() {
        var thisArgs = args.concat();
        for (var i = 0,
            il = arguments.length; i < il; i++) {
            thisArgs.push(arguments[i]);
        }
        return method.apply(_this, thisArgs);
    };
};
Function.prototype.timeout = function(time) {	//延时执行
    if ($.browser.mozilla) {
        var f = this;
        return setTimeout(function() {
            f();
        },
        time * 1000);
    }
    return setTimeout(this, time * 1000);
};
Function.prototype.interval = function(time) {	//循环执行
    return setInterval(this, time * 1000);
};
Function.prototype.bindEvent = function() {	//绑定Event
    var method = this,
    _this = arguments[0],
    args = [];
    for (var i = 1,
        il = arguments.length; i < il; i++) {
        args.push(arguments[i]);
    }
    return function(e) {
        var thisArgs = args.concat();
        thisArgs.unshift(e || window.event);
        return method.apply(_this, thisArgs);
    };
};

//数组扩展
Array.prototype.include = function(value) {		//是否包含
    if(this.constructor != Array) return;
    return this.index(value) != -1;
};
Array.prototype.index = function(value) {	//查找值索引
    for (var i = 0,
        il = this.length; i < il; i++) {
        if (this[i] == value) return i;
    }
    return -1;
};
Array.prototype.unique = function() {	//删除重复
    for (var i = 0; i < this.length; i++) {
        var it = this[i];
        for (var j = this.length - 1; j > i; j--) {
            if (this[j] == it) this.splice(j, 1);
        }
    }
    return this;
};
Array.prototype.del = function(obj) {	//删除元素
    if(this.constructor != Array) return;
    var index = this.index(obj);
    if (index >= 0 && index < this.length) {
        this.splice(index, 1);
    }
    return this;
};
//字符串扩展
String.prototype.trim = function() {		//是否包含
    return $.trim(this);
};

$(function(){
    //当窗口放大或缩小时触发的事件
    if($('#zoomstate').size()>0){
        level = 1;
        $(window).resize(function(){
            SG.tools.zoomChange($('#zoomstate'));
        });
    }
});

function urldecode(str){
    var ret=str;
    ret=ret.replace(/\+/g,'%20');
    ret=decodeURIComponent(ret);
    ret=ret.toString();
    return ret;
}
function urlencode(str){
    var ret=str;
    ret=ret.toString();
    ret=encodeURIComponent(ret);
    ret=ret.replace(/%20/g,'+');
    return ret;
}